package com.cj.myblog.plugin;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jujun chen
 * @Description: FreeMarker字符串解析器
 * @Date: 2017/10/30
 */
public class StringTemplate implements TemplateLoader{

    private static final String DEFAULT_TEMPLATE_KEY = "_default_template_key";

    private Map templates = new HashMap();

    public StringTemplate(String defaultTemplate) {
        if (defaultTemplate != null && !defaultTemplate.equals("")) {
            templates.put(DEFAULT_TEMPLATE_KEY, defaultTemplate);
        }
    }


    public void addTemplate(String name, String template) {
        if (name == null || template == null || name.equals("")
                || template.equals("")) {
            return;
        }
        if (!templates.containsKey(name)) {
            templates.put(name, template);
        }
    }


    @Override
    public void closeTemplateSource(Object templateSource)
            throws IOException {

    }


    @Override
    public Object findTemplateSource(String name) throws IOException {
        if (name == null || name.equals("")) {
            name = DEFAULT_TEMPLATE_KEY;
        }
        return templates.get(name);
    }


    @Override
    public long getLastModified(Object templateSource) {
        return 0;
    }


    @Override
    public Reader getReader(Object templateSource, String encoding)
            throws IOException {
        return new StringReader((String) templateSource);
    }


    public  static String convertTplStr(Map<String,Object> model,String tpl){

        Configuration cfg = new Configuration();

        cfg.setTemplateLoader(new StringTemplate(tpl));

        cfg.setDefaultEncoding("UTF-8");

        Template template = null;

        StringWriter tplWriter = new StringWriter();

        try {
            template = cfg.getTemplate("");

            template.process(model, tplWriter);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return tplWriter.toString();
    }


}
